/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.hazard.alarm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.basic.common.api.feign.RemoteParkBasicDictService;
import com.hopes.bizz.basic.hazard.source.entity.HazMonitorFactorEntity;
import com.hopes.bizz.common.core.util.DateUtils;
import com.hopes.bizz.hazard.alarm.dto.HazAlarmBrokenExcelDTO;
import com.hopes.bizz.hazard.alarm.entity.HazAlarmBrokenEntity;
import com.hopes.bizz.hazard.alarm.mapper.HazAlarmBrokenMapper;
import com.hopes.bizz.hazard.alarm.service.HazAlarmBrokenService;
import com.hopes.bizz.hazard.alarm.vo.HazAlarmBrokenExcelVO;
import com.hopes.bizz.hazard.common.constant.HazardDicConstant;
import com.hopes.bizz.hazard.om.entity.HazRtDataEntity;
import com.hopes.bizz.hazard.om.service.HazRtDataService;
import com.hopes.boss.common.core.constant.SecurityConstants;
import com.hopes.boss.common.data.resolver.ParamResolver;
import com.hopes.boss.common.entity.ValidateImportBO;
import com.hopes.boss.common.excel.vo.ErrorMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 危险源断网报警
 *
 * @author daijie
 * @date 2023-11-16 19:21:03
 */
@Service
public class HazAlarmBrokenServiceImpl extends ServiceImpl<HazAlarmBrokenMapper, HazAlarmBrokenEntity> implements HazAlarmBrokenService {

    @Autowired
    @Lazy
    private HazRtDataService hazRtDataService;

    @Resource
    private RemoteParkBasicDictService remoteParkBasicDictService;

    @Override
    public ValidateImportBO<HazAlarmBrokenExcelDTO> validateImport(List<HazAlarmBrokenExcelDTO> excelDTOList) {
        ValidateImportBO<HazAlarmBrokenExcelDTO> bo = new ValidateImportBO<>();
        List<ErrorMessage> errorMessageList = new ArrayList<>();
        List<HazAlarmBrokenExcelDTO> saveList = new ArrayList<>(excelDTOList);
        int successNum = excelDTOList.size();
        int failedNum = 0;

        bo.setErrorMessages(errorMessageList);
        bo.setSaveList(saveList);
        bo.setSuccessNum(successNum);
        bo.setFailedNum(failedNum);
        return bo;
    }

    @Override
    public HazAlarmBrokenEntity importDtoToEntity(HazAlarmBrokenExcelDTO excelDto) {
        HazAlarmBrokenEntity entity = new HazAlarmBrokenEntity();
        BeanUtils.copyProperties(excelDto, entity);
        return entity;
    }

    @Override
    public HazAlarmBrokenExcelVO exportEntityToVo(HazAlarmBrokenEntity entity) {
        HazAlarmBrokenExcelVO excelVO = new HazAlarmBrokenExcelVO();
        BeanUtils.copyProperties(entity, excelVO);
        return excelVO;
    }

    @Override
    public Boolean alarmBrokenJobHandler() {
        // step.1 查询全部正在使用的危险源监控因子
        List<HazMonitorFactorEntity> monitorFactorList = remoteParkBasicDictService.getHazMonitorFactorList(SecurityConstants.FROM_IN).getData();

        Long alarmTimes = ParamResolver.getLong("HAZARD_ALARM_TIMES", 5L);
        Date now = new Date();
        for (HazMonitorFactorEntity monitorFactor : monitorFactorList) {
            // step.2 查询当前实时数据
            HazRtDataEntity rtData = hazRtDataService.getOne(Wrappers.lambdaQuery(HazRtDataEntity.class).eq(HazRtDataEntity::getMonitorFactorId, monitorFactor.getId()));

            // 没有实时数据直接构造报警
            if (rtData == null) {
                saveOrUpdateAlarmBroken(monitorFactor, now, 0L);
                continue;
            }

            Date dataTime = rtData.getDataTime();
            Long min = DateUtils.getIntervalMin(dataTime, now);

            if (min > alarmTimes) {
                saveOrUpdateAlarmBroken(monitorFactor, now, min);
            } else {
                clearAlarmNetIfExist(monitorFactor);
            }
        }
        return true;
    }

    private void saveOrUpdateAlarmBroken(HazMonitorFactorEntity monitorFactor, Date now, Long min) {
        // 是否已经有报警
        LambdaQueryWrapper<HazAlarmBrokenEntity> alarmBrokenWrapper = Wrappers.lambdaQuery();
        alarmBrokenWrapper.eq(HazAlarmBrokenEntity::getMonitorFactorId, monitorFactor.getId());
        alarmBrokenWrapper.eq(HazAlarmBrokenEntity::getAlarmStatus, HazardDicConstant.HAZ_ALARM_STATUS_ALARM);
        HazAlarmBrokenEntity exist = this.getOne(alarmBrokenWrapper, false);

        if (exist != null) {
            String handleStatus = exist.getHandleStatus();
            if (Objects.equals(handleStatus, HazardDicConstant.HAZ_ALARM_HANDLE_STATUS_TODO)) {
                // 更新持续时间和报警级别
                exist.setDurationTime(min);
                exist.setAlarmContent(buildAlarmContent(exist.getAlarmTimeStr(), monitorFactor.getFactorName()));
                this.updateById(exist);
                updateMonitorFactorAlarmStatus(monitorFactor, true);
                return;
            }
            // 已经处理的就构造新的报警
        }
        // 新造报警
        HazAlarmBrokenEntity alarmBrokenEntity = new HazAlarmBrokenEntity();
        alarmBrokenEntity.setAlarmTime(now);
        alarmBrokenEntity.setDurationTime(min);
        alarmBrokenEntity.setAlarmStatus(HazardDicConstant.HAZ_ALARM_STATUS_ALARM);
        alarmBrokenEntity.setHandleStatus(HazardDicConstant.HAZ_ALARM_HANDLE_STATUS_TODO);
        alarmBrokenEntity.setHazardSourceId(monitorFactor.getHazardSourceId());
        alarmBrokenEntity.setMonitorFactorId(monitorFactor.getId());
        alarmBrokenEntity.setOrgId(monitorFactor.getOrgId());

        alarmBrokenEntity.setAlarmContent(buildAlarmContent(alarmBrokenEntity.getAlarmTimeStr(), monitorFactor.getFactorName()));
        this.save(alarmBrokenEntity);
        updateMonitorFactorAlarmStatus(monitorFactor, true);

//        MessageDO messageDO = new MessageDO();
//        messageDO.setNeedBroadcast(Boolean.TRUE);
//        messageDO.setTenantId(TenantContextHolder.getTenantId().toString());
//        messageDO.setMessageText(alarmBrokenEntity.getAlarmContent());
//        RedisMessageDistributor messageDistributor = SpringContextHolder.getBean(RedisMessageDistributor.class);
//        messageDistributor.distribute(messageDO);
    }

    private void clearAlarmNetIfExist(HazMonitorFactorEntity monitorFactor) {
        // 是否已经有报警
        LambdaQueryWrapper<HazAlarmBrokenEntity> alarmBrokenWrapper = Wrappers.lambdaQuery();
        alarmBrokenWrapper.eq(HazAlarmBrokenEntity::getMonitorFactorId, monitorFactor.getId());
        alarmBrokenWrapper.eq(HazAlarmBrokenEntity::getAlarmStatus, HazardDicConstant.HAZ_ALARM_STATUS_ALARM);
        HazAlarmBrokenEntity exist = this.getOne(alarmBrokenWrapper, false);

        // 消除报警
        if (exist != null) {
            exist.setAlarmStatus(HazardDicConstant.HAZ_ALARM_STATUS_REMOVE);
            exist.setRemoveTime(new Date());
            this.updateById(exist);
        }

        updateMonitorFactorAlarmStatus(monitorFactor, false);
    }

    private void updateMonitorFactorAlarmStatus(HazMonitorFactorEntity monitorFactor, boolean flag) {
        monitorFactor.setAlarmBrokenNet(flag);
        remoteParkBasicDictService.updateHazMonitorFactorById(monitorFactor, SecurityConstants.FROM_IN);
    }

    private String buildAlarmContent(String date, String monitorFactor) {
        StringBuilder sb = new StringBuilder("[断网]");
        sb.append(monitorFactor);
        sb.append(", 开始时间:").append(date);
        sb.append(", 请及时处理!");
        return sb.toString();
    }
}
